package util

import (
	"time"

	"gitee.com/konyshe/gogo"
)

type Monitor struct {
	downStreamDataSize int // 单位时间内下行的总字节数
	upStreamDataSize   int // 单位时间内上行的总字节数
}

func NewMonitor() *Monitor {
	c := new(Monitor)
	c.Init()

	// 开启子线程，每一秒计算一次该秒内的数据包大小平均值，并将下载、上传总量置零
	//c.Start()

	return c
}

func (c *Monitor) Init() {
	c.downStreamDataSize = 0
	c.upStreamDataSize = 0
}

// 每一秒计算一次该秒内的数据包大小平均值，并将下载、上传总量置零
func (c *Monitor) Start() {
	go func() {
		for {
			gogo.LogInfoF("\rDown:%.2fkb/s \t Up:%.2fkb/s\n", float32(c.GetDown())/1024/1, float32(c.GetUp())/1024/1)
			c.downStreamDataSize = 0
			c.upStreamDataSize = 0
			time.Sleep(1 * time.Second)
		}
	}()
}

func (c *Monitor) SetUp(len int) {
	c.upStreamDataSize += len // 统计下行封包总大小
}

func (c *Monitor) GetUp() float32 {
	r := float32(c.upStreamDataSize)
	c.upStreamDataSize = 0
	return r
}

func (c *Monitor) SetDown(len int) {
	c.downStreamDataSize += len // 统计下行封包总大小
}

func (c *Monitor) GetDown() float32 {
	r := float32(c.downStreamDataSize)
	c.downStreamDataSize = 0
	return r
}

func (c *Monitor) Reset() {
	c.upStreamDataSize = 0
	c.downStreamDataSize = 0
}
